const { Service } = require('egg')
const iconv = require('iconv-lite') // 导入iconv-lite模块
const { tableToList } = require('../utils/tools')

module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/cssfjw/taglib/DataTable.jsp?tableId=2508`

    const res1 = await this.ctx.curl(`${this.ctx.state.baseUrl}/cssfjw/jw/common/getStuGradeSpeciatyInfo.action`, {
      method: 'POST',
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/pyfa.llkc.html?menucode=S20101',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const resultObj = JSON.parse((JSON.parse(iconv.decode(res1.data, 'gbk'))).result)
    const [nj, dwh, zydm] = [resultObj.nj, resultObj.dwh, resultObj.zydm]

    const res2 = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        nj_: nj,
        yxdm: dwh,
        zydm,
      },
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/pyfa.llkc.html?menucode=S20101',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })

    const gbkString = iconv.decode(res2.data, 'gbk')

    const header = ['课程名称', '学分', '性质/类别', '学时', '考核方式', '周学时']
    // "header":["课程名称", "性质", "类别", "学分", "考核方式", "学时", "开课院系"],

    if (res2.status === 200) {
      try {
        const data2 = tableToList(gbkString, 'tbody')
        // console.log('data2', data2);

        // 开始处理
        let k = 0
        const dataxq = data2.slice()// 复制一份单独的数据
        const xq = []// 保存学期
        for (const i of dataxq) {
          if (i[1] !== '') {
            if (i[1].includes('学年第一学期')) {
              i[1] = i[1].replace('学年第一学期', '-1')
            } else if (i[1].includes('学年第二学期')) {
              i[1] = i[1].replace('学年第二学期', '-2')
            }// 保存学期
            xq.push(i[1])
          }
        }
        const dataUp = Array.from({ length: xq.length + 1 }, () => [])// 保存每个学期的数据
        for (const i of data2) {
          i[2] = i[2].replace(/\[.*?\]/g, '')
          if (i[1] === '') {
            dataUp[k].push(i)
          } else if (i[1] !== '') {
            k++
            dataUp[k].push(i)
          }
        }
        for (const i in data2) { // 去掉多余的数据
          data2[i].splice(0, 2)
          data2[i].splice(3, 1)
          data2[i].splice(5, 4)
          data2[i].splice(6, 2)
        }
        for (const q of dataUp) { // 处理内部数据
          for (const i of q) {
            if (i.length !== 0) {
              i[2] = i[2].replace(/课/g, '');
              [i[3], i[4]] = [i[4], i[3]]
            }
          }
        }
        dataUp.shift()
        // console.log('dataUp', dataUp);
        const dataJson = {}
        for (let i = 0; i < xq.length; i++) { // 构成json
          dataJson[xq[i]] = dataUp[i]
        }
        // console.log('dataJson', dataJson);
        // 结束处理
        return { table: dataJson, header }
      } catch (err) {
        return err
      }
    }
    return { table: {}, header }
  }
}
